﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net;
using System.Net.Sockets;
using BLL;
using System.Threading;

namespace SocketProgram
{
    class Program
    {
        private const int port = 5554;
        private const String host = "59.65.170.179";

        public static char PARAMETER_SPLITTER = '|';

        public static String LOGIN_REQUEST  = "{[LOGIN_REQUEST]}";
        public static String LOGIN_SUCCEED  = "{[LOGIN_SUCCEED]}";
        public static String LOGIN_FAIL     = "{[LOGIN_FAIL]}";
        public static String DETAIL_REQUEST = "{[DETAIL_REQUEST]}";
        public static String FINDPWD_REQUEST= "{[FINDPWD_REQUEST]}";
        public static String FINDPWD_SUCCEED= "{[FINDPWD_SUCCEED]}";
        public static String FINDPWD_FAIL   = "{[FINDPWD_FAIL]}";

        static void Main(String[] args)
        {
                try
                {
                    IPAddress ip = IPAddress.Parse(host);
                    IPEndPoint ipe = new IPEndPoint(ip, port);

                    // 开启socket服务端口
                    Socket s = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);

                    // 绑定并开始监听
                    s.Bind(ipe);
                    s.Listen(0);

                    // 有连接则开启线程为其服务
                    while(true)
                    {
                        Console.WriteLine("Server started. Waiting for a connection...");
                        Socket soc = s.Accept();
                        Console.WriteLine("Connected with a client");
                        IMovieServerTask task = new IMovieServerTask(soc);
                        new Thread(new ThreadStart(task.Run)).Start();
                    }

                    
                }
                catch (ArgumentNullException e)
                {
                    Console.WriteLine("ArgumentNullException:{0}", e);
                }
                catch (SocketException e)
                {
                    Console.WriteLine("SocketException:{0}", e);
                }
                Console.WriteLine("Press Enter to Exit");
                Console.ReadLine();
        }

        private class IMovieServerTask
        {
            private Socket soc;

            public IMovieServerTask(Socket socket)
            {
                this.soc = socket;
            }

            public void Run()
            {
                while (true)
                {
                    String returnMesg = "";
                    String info = "";

                    //从客户端接受信息
                    String recvStr = "";
                    byte[] recvBytes = new byte[1024];
                    int bytes = soc.Receive(recvBytes, recvBytes.Length, 0);
                    recvStr += Encoding.ASCII.GetString(recvBytes, 0, bytes);

                    Console.WriteLine("Obtain message from client:{0}", recvStr);

                    if (recvStr.StartsWith(LOGIN_REQUEST))
                    {
                        recvStr = recvStr.Substring(LOGIN_REQUEST.Length);
                        String username = recvStr.Split(PARAMETER_SPLITTER)[0];
                        String password = recvStr.Split(PARAMETER_SPLITTER)[1];
                        KeyValuePair<bool, String> pair = BLL.user.UserManager.Login(username, password);
                        info = pair.Value;
                        if (pair.Key)
                        {
                            returnMesg = LOGIN_SUCCEED + info;
                        }
                        else
                        {
                            returnMesg = LOGIN_FAIL + info;
                        }
                    }
                    else if (recvStr.StartsWith(DETAIL_REQUEST))
                    {
                        recvStr = recvStr.Substring(DETAIL_REQUEST.Length);
                        String id = recvStr;
                        returnMesg = BLL.videoLib.VideoManager.GetDetailById_Android(Int32.Parse(id));
                    }

                    byte[] bs = Encoding.UTF8.GetBytes(returnMesg + "\n");
                    Console.WriteLine("Response: " + returnMesg);
                    soc.Send(bs, bs.Length, 0);
                }
            }
        }
    }
}
